from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response, get_object_or_404
from django.views.generic.list_detail import object_list

from taggit.models import TaggedItem, Tag
from exchange.models import Event
from polls.models import Poll
from django.template import RequestContext

# List all tags
def index(request):
  tags = Tag.objects.all()
  return render_to_response('taggit/index.html', {
    'tags': tags,
  }, context_instance=RequestContext(request))
  
def detail(request, tag):
  polls = Poll.objects.filter(tags__name=tag)
  events = Event.objects.filter(tags__name=tag)
  return render_to_response('taggit/detail.html', {
      'user': request.user,
      'polls': polls,
      'events': events,
  }, context_instance=RequestContext(request))


def tagged_object_list(request, slug, queryset, **kwargs):
    if callable(queryset):
        queryset = queryset()
    tag = get_object_or_404(Tag, slug=slug)
    qs = queryset.filter(pk__in=TaggedItem.objects.filter(
        tag=tag, content_type=ContentType.objects.get_for_model(queryset.model)
    ).values_list("object_id", flat=True))
    if "extra_context" not in kwargs:
        kwargs["extra_context"] = {}
    kwargs["extra_context"]["tag"] = tag
    return object_list(request, qs, **kwargs)
